import React from 'react';
import InputLabel from '@material-ui/core/InputLabel';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControl from '@material-ui/core/FormControl';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import { BlackInput } from '../base/st';
import { makeStyles } from '@material-ui/core/styles';
import { is_empty, obj_str } from 'sui';

const useStyles = makeStyles((theme) => ({
    formControl: {
        marginTop: theme.spacing(2),
        margin: theme.spacing(1),
        minWidth: 220,
    },
}));

/* lst = [
 *   {id: "xx", des: "xx"}
 * ]
*/
const NuiSelect = ({ mod, lst, handleMod, width=261, className="mt-2", name }) => {
    const handleChange = event => {
        if (handleMod) {
            handleMod(event.target.value);
        }
    };

    const item = () => {
        if (is_empty(lst)) {
            return null;
        }

        return lst.map(d => <MenuItem key={d.id} value={d.id}>{d.des}</MenuItem>);
    };

    return (
        <Select value={mod || ""} name={name} onChange={handleChange} input={<BlackInput/>} className={className}>
            {item()}
        </Select>
    );
};

const SelectLabel = ({ className, value, setValue, label, lst, name }) => {
    return (
        <div className={"text-xl inline-flex items-center " + className}>
            <div>{label}</div>
            <NuiSelect
                className={"ml-3 text-xl"}
                mod={value}
                name={name}
                lst={lst}
                handleMod={(v) => setValue(v)}
                width={150}/>
        </div>
    );
};

/* lst = [
 *   {id: "xx", des: "xx"}
 * ]
*/
const IkSelect = ({ form, value, label, lst, name, className, st="formControl" }) => {
    const classes = useStyles();

    const item = () => {
        if (is_empty(lst)) {
            return null;
        }

        return lst.map(d => <MenuItem key={d.id} value={d.id}>{d.des}</MenuItem>);
    };

    return (
        <div className={className}>
            <FormControl variant="outlined" className={classes[st]} error={Boolean(form.err[name])}>
                <InputLabel>{label}</InputLabel>
                <Select
                    value={obj_str(value, name)}
                    name={name}
                    label={label}
                    onChange={event => form.hcmd(event.target.name, event.target.value)}>
                    {item()}
                </Select>
                <FormHelperText>{obj_str(form.err, name)}</FormHelperText>
            </FormControl>
        </div>
    );
};

export {IkSelect, SelectLabel};
